<template>
  <base-page :title="title" backgroundColor="#F5F5F5" :customGoBackFn="goBack">
    <view class="mx-16 flex-col">
      <view class="mt-16">
        <text class="fs-16 text-bold">活动介绍</text>
      </view>
      <view class="flex flex-col mt-16">
        <view>
          <text class="text-bold">活动图片</text><text class="text-color-hint">（拖拽可调整顺序）</text>
        </view>
        <drag-image v-model="files" keyName="url" isShowFirst :imageWidth="180" :padding="20" :borderRadius="12" :addImage="toChooseFile" :delImage="delImage"></drag-image>
      </view>
      <view class="mt-16">
        <view class="mb-8"><text class="text-bold">活动标题</text></view>
        <view class="uni-bg-white radius-8 p-12">
          <textarea class="text-color-regular fs-14" :maxlength="60" v-model="formData.activeTitle" placeholder-style="color:#A5A7A9;" placeholder="*请输入活动标题（最多60字）" :auto-height="true" />
          <view class="line my-12"></view>
          <rich-editor ref="richEditor" v-model="formData.activeContents" :uploadFilePurpose="2" placeholder="*请输入活动内容"></rich-editor>
        </view>
      </view>
      <view class="mt-20">
        <view class="mb-8"><text class="text-bold">活动设置</text></view>
        <view class="radius-8 uni-bg-white py-12 px-16 flex-col">
          <Datetimerange title="活动时间" :value="activeDatetimerange" :disableStartTip="isNotStart ? '活动即将开始，不支持修改' : '活动进行中，无法修改'" @change="onActiveDatetimeChange" isDefaultTime />
          <Datetimerange class="mt-16" title="使用时间" :disableTip="isNotStart ? '活动即将开始，不支持修改' : '活动进行中，无法修改'" :value="validDatetimerange" @change="onValidDatetimeChange" isDefaultTime />
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">拼团价格</text>
            <view class="flex item-center">
              <input v-model="formData.groupBuyPrice" @blur="formData.groupBuyPrice = numberFormat($event.detail.value)" :disabled="isZeroState || isOngoing" class="text-color-regular fs-14 text-right" type="digit" :maxlength="8" placeholder="请输入价格" placeholder-class="text-color-hint" />
            </view>
          </view>
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">单买价格</text>
            <input v-model="formData.activePrice" @blur="formData.activePrice = numberFormat($event.detail.value)" :disabled="isNotStart || isOngoing" class="text-color-regular fs-14 text-right" type="digit" :maxlength="8" placeholder="请输入价格" placeholder-class="text-color-hint" />
          </view>
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">成团人数</text>
            <input v-model="formData.groupNum" :disabled="isNotStart" class="text-color-regular fs-14 text-right" type="number" :maxlength="8" placeholder="请输入成团人数" placeholder-class="text-color-hint" />
          </view>
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">成团时间</text>
            <view class="flex item-center">
              <input v-model="formData.groupDuration" :disabled="isNotStart" class="text-color-regular fs-14 text-right" type="digit" :maxlength="8" placeholder="请输入成团时间" placeholder-class="text-color-hint" />
              <view class="flex item-center">
                小时
              </view>
            </view>
          </view>
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">开团权限</text>
            <view class="flex item-center">
              <view class="flex item-center" @click="changeGroupCreatorPermission()">
                <image v-if="formData.groupCreatorPermission === 'ALL'" class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-selected.svg"></image>
                <image v-else class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-default.svg"></image>
                所有人
              </view>
              <view class="flex item-center" @click="changeGroupCreatorPermission()">
                <image v-if="formData.groupCreatorPermission === 'LEVEL1_AGENT'" class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-selected.svg"></image>
                <image v-else class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-default.svg"></image>
                仅一级经纪人
              </view>
            </view>
          </view>
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">活动库存</text>
            <input v-model="formData.totalStock" :disabled="isNotStart" class="text-color-regular fs-14 text-right" type="number" :maxlength="8" placeholder="请输入库存" placeholder-class="text-color-hint" />
          </view>
          <view>
            <view class="flex justify-between item-center h-20 mt-16">
              <text class="text-color-regular">虚拟销量</text>
              <input v-model="formData.virtualSaleNum" :disabled="isNotStart" class="text-color-regular fs-14 text-right" type="number" :maxlength="8" placeholder="不设置则显示实际销量" placeholder-class="text-color-hint" />
            </view>
            <view class="flex-col">
              <text class="fs-10 text-color-hint">活动页面销量=虚拟销量+实际销量</text>
            </view>
          </view>
          <view class="flex justify-between item-center mt-16">
            <view class="flex-col">
              <text class="text-color-regular">虚拟成团</text>
              <text class="fs-10 text-color-hint">成团时间到，未满员的拼团将自动加入机器人成团</text>
            </view>
            <view>
              <image v-if="formData.virtualGroup === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('virtualGroup', false)"></image>
              <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('virtualGroup', true)"></image>
            </view>
          </view>

          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular mr-20 flex-shrink">下单限购设置</text>
            <input v-model="formData.limitBuyNum" :disabled="isNotStart" class="flex-1 text-color-regular fs-14 text-right" type="number" :maxlength="8" placeholder="每个用户限购数量,不填不限制" placeholder-class="text-color-hint" />
          </view>
          <view class="flex justify-between item-center mt-16">
            <view class="flex-col">
              <text class="text-color-regular">过期自动退款</text>
              <text class="fs-10 text-color-hint">订单过期未核销自动退款</text>
            </view>
            <view>
              <image v-if="formData.autoRefundEnabled === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('autoRefundEnabled', false)">
              </image>
              <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('autoRefundEnabled', true)"></image>
            </view>
          </view>
          <view class="flex justify-between item-center mt-16">
            <view class="flex-col">
              <text class="text-color-regular">隐藏链接</text>
              <text class="fs-10 text-color-hint">开启后，仅可通过分享的链接进入活动</text>
            </view>
            <view>
              <image v-if="formData.hideLink === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('hideLink', false)"></image>
              <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('hideLink', true)"></image>
            </view>
          </view>

          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular mr-20 flex-shrink">活动地点</text>
            <view class="flex justify-end item-center flex-1 w-0" @click="toChooseLocation">
              <image class="w-16 h-16 mr-4 flex-shrink" src="@/static/svg/activity/icon-location.svg">
              </image>
              <text v-if="formData.address" class="text-color-hint mr-4 text-right text-cut">{{
								formData.address }}</text>
              <text v-else class="text-color-hint mr-4">未选择</text>
              <image class="w-16 h-17 flex-shrink" src="@/static/svg/icon-arrow-right.svg"></image>
            </view>
          </view>
        </view>
        <view class="mt-20">
          <view class="mb-8"><text class="text-bold">报名设置</text></view>
          <view class="radius-8 uni-bg-white py-12 px-16 flex-col">
            <view class="flex justify-between item-center">
              <view class="flex-col">
                <text class="text-color-regular">开启报名</text>
              </view>
              <view>
                <image v-if="formData.enrollEnable === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('enrollEnable', false)">
                </image>
                <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('enrollEnable', true)"></image>
              </view>
            </view>
            <template v-if="formData.enrollEnable === 1">
              <view class="flex justify-between item-center h-20 mt-16">
                <text class="text-color-regular">核销方式</text>
                <view class="flex">
                  <view v-if="formData.verifyType !== 1" class="flex item-center mr-24" @click="changeVerifyMethod(1)">
                    <image v-if="formData.verifyMethod === 1" class="w-12 h-12 mr-4" src="@/static/svg/radio-selected.svg"></image>
                    <image v-else class="w-12 h-12 mr-4" src="@/static/svg/radio-default.svg">
                    </image>
                    <text>线上核销</text>
                  </view>
                  <view class="flex item-center" @click="changeVerifyMethod(2)">
                    <image v-if="formData.verifyMethod === 2" class="w-12 h-12 mr-4" src="@/static/svg/radio-selected.svg"></image>
                    <image v-else class="w-12 h-12 mr-4" src="@/static/svg/radio-default.svg">
                    </image>
                    <text>线下核销</text>
                  </view>
                </view>
              </view>
              <view class="mt-8 text-color-hint fs-10">
                <view>线上核销：需报名用户手动确认参与，确认后不可取消不可退款；</view>
                <view>线下核销：报名用户线下核销，未核销自动退款；</view>
              </view>
              <view v-if="formData.enrollEnable !== 1" class="flex justify-between item-center mt-16">
                <view class="flex-col">
                  <text class="text-color-regular">是否需要签到</text>
                  <text class="fs-10 text-color-hint">消费者需要扫码核销进行签到</text>
                </view>
                <view>
                  <image v-if="formData.signInRequired === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('signInRequired', false)"></image>
                  <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('signInRequired', true)"></image>
                </view>
              </view>
              <view class="flex justify-between item-center h-20 mt-16">
                <text class="text-color-regular">签到费用</text>
                <input v-model="formData.signInFee" @blur="formData.signInFee = numberFormat($event.detail.value)" class="text-color-regular fs-14 text-right" type="digit" :maxlength="8" placeholder="不设置默认0" placeholder-class="text-color-hint" />
              </view>
            </template>

          </view>
        </view>
      </view>
      <form-editor v-if="formData.enrollEnable === 1" v-model="formData.activeEnrollInfos" :disabled="isNotStart" title="报名信息" class="mt-20">
      </form-editor>

      <view v-if="formData.enrollEnable === 1" class="uni-bg-white py-12 px-16 c3 fs-12 radius-8" style="margin-top: -8px;">
        <view class="flex justify-between item-center mt-16">
          <view class="flex-col">
            <text class="text-color-regular">报名信息团长可见</text>
            <text class="fs-10 text-color-hint">团长可查看拼团成员填写报名信息</text>
          </view>
          <view>
            <image v-if="formData.leadViewEnrollInfo === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('leadViewEnrollInfo', false)">
            </image>
            <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('leadViewEnrollInfo', true)"></image>
          </view>
        </view>
      </view>

      <view v-if="isGroup && formData.enrollEnable === 1" class="mt-20">
        <view class="mb-8">
          <text class="text-bold">活动联系信息</text>
          <text class="text-color-hint">（至少填写一项）</text>
        </view>
        <view class="radius-8 uni-bg-white py-12 px-16 flex-col">
          <view class="flex justify-between item-center h-20">
            <text class="text-color-regular">联系电话</text>
            <input v-model="formData.activeMobile" class="text-color-regular fs-14 text-right" type="tel" :maxlength="13" placeholder="请输入活动联系电话" placeholder-class="text-color-hint" />
          </view>
          <view class="flex justify-between item-center h-20 mt-16">
            <text class="text-color-regular">客服微信号</text>
            <input v-model="formData.activeWechat" class="text-color-regular fs-14 text-right" type="text" placeholder="请输入客服微信号" placeholder-class="text-color-hint" />
          </view>
        </view>
      </view>
      <GoodsTable v-model="activeGoods" :disable="!isDraft" class="mt-20" />
      <view v-if="activeGoods.length" class="flex justify-between item-center h-20 mt-16">
        <text class="text-color-regular">补贴设置</text>
        <view class="flex justify-end item-center" @click="toSubsidySetting">
          <text class="text-color-hint">{{ SubsidyDict[formData.subsidyState] }}</text>
          <image class="w-16 h-17 ml-4" src="@/static/svg/icon-arrow-right.svg"></image>
        </view>
      </view>
      <view v-if="isGroup" class="flex item-center mt-4 flex-wrap">
        <view v-for="(tag, index) in formData.labels" :key="index" class="tag-view uni-bg-white mr-12 mt-12">
          <view class="fs-14 bg-secondary-info text-white radius-16 px-16 py-4">{{ tag.name }}</view>
          <image class="w-13 h-13" src="@/pagesB/static/activity/del-icon.svg" @click="formData.labels.splice(i, 1)">
          </image>
        </view>
        <view v-if="formData && formData.labels && formData.labels.length < 3" class="tag-view uni-bg-white mt-12" @click="open">
          <view class="fs-14 border-secondary-info color-secondary-info radius-16 px-16 py-4">#添加标签</view>
        </view>
      </view>
      <view class="mt-20">
        <view class="mb-8"><text class="text-bold">分销设置</text></view>
        <view class="radius-8 uni-bg-white py-12 px-16 flex-col">
          <view class="flex justify-between item-center">
            <text class="text-color-regular">开启分销</text>
            <view>
              <image v-if="formData.agentState === 2" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('agentState', false)"></image>
              <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('agentState', true)"></image>
            </view>
          </view>
          <view v-if="formData.agentState === 2" class="mt-8 flex justify-between item-center pl-12 fs-12">
            <text class="text-color-regular">分销佣金</text>
            <view class="flex item-center" @click="toDistributionSetting">
              <text class="text-color-hint">
                {{ formData.rewardType === 3 ? formData.rewardPoints + '积分' :
								formData.rewardType
								=== 1 ? (numberFormat(formData.commissionRate * formData.groupBuyPrice) / 100).toFixed(2)
								:
								'设置分销佣金' }}
                <!-- {{commission > 0 ? `¥${numberFormat(commission)}` : '设置分销佣金'}} -->
              </text>
              <image class="w-12 h-12" src="@/static/svg/icon-arrow-right.svg"></image>
            </view>
          </view>
        </view>
      </view>
      <view class="mt-20">
        <view class="mb-8"><text class="text-bold">营销设置</text></view>
        <view class="radius-8 uni-bg-white py-12 px-16 flex-col">
          <view class="flex justify-between item-center h-20">
            <view class="flex-col">
              <text class="text-color-regular">定向免单</text>
              <text class="fs-10 text-color-hint">可指定成团后，团长免单或团员随机免单</text>
            </view>
            <view class="flex item-center">
              <view class="flex item-center" @click="onSwitchClick('freeType',1)">
                <image v-if="formData.freeType === 1" class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-selected.svg"></image>
                <image v-else class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-default.svg"></image>
                团长免单
              </view>
              <view class="flex item-center" @click="onSwitchClick('freeType',2)">
                <image v-if="formData.freeType === 2" class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-selected.svg"></image>
                <image v-else class="ml-6 w-14 h-14 mr-4" src="@/static/svg/radio-default.svg"></image>
                随机免单
              </view>
            </view>
          </view>
          <view class="flex justify-between item-center h-20 mt-24">
            <view class="flex-col">
              <text class="text-color-regular">团长0元开团</text>
              <text class="fs-10 text-color-hint">团长开团无需下单</text>
            </view>
            <view>
              <image v-if="formData.leadFreeEnabled === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('leadFreeEnabled', false)">
              </image>
              <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('leadFreeEnabled', true)"></image>
            </view>
          </view>
          <view class="flex justify-between item-center h-20 mt-24">
            <view class="flex-col">
              <text class="text-color-regular">直接参团</text>
              <text class="fs-10 text-color-hint">拼团页面展示别人已开的团，陌生人可直接参与</text>
            </view>
            <view>
              <image v-if="formData.directJoinEnabled === 1" class="w-32 h-16" src="@/static/svg/switch-on.svg" @click="onSwitchClick('directJoinEnabled', false)">
              </image>
              <image v-else class="w-32 h-16" src="@/static/svg/switch-default.svg" @click="onSwitchClick('directJoinEnabled', true)"></image>
            </view>
          </view>
          <view class="flex justify-between item-center h-20 mt-24">
            <text class="text-color-regular">新人首单红包</text>
            <text v-if="!formData.activeRedPacket" class="text-color-hint" @click="toRedPacketSetting">首单专享
              提高转化</text>
            <view v-else class="flex item-center" @click="toRedPacketSetting">
              <text class="text-color-regular">新人首单立减{{ formData.activeRedPacket.firstRedPacketAmt
								}}元</text>
              <image class="w-16 h-17 ml-4" src="@/static/svg/icon-arrow-right.svg"></image>
            </view>
          </view>
        </view>
      </view>
    </view>
    <template #footer>
      <view class="m-12 flex">
        <button class="mr-12 flex-1 inline-flex center py-12 uni-bg-white radius-8 border-secondary-info color-secondary-info fs-16 font-normal leading-22" @click="toRelease(1)">保存并预览</button>
        <button class="flex-1 inline-flex center py-12 bg-primary radius-8 text-white fs-16 font-normal leading-22" @click="toRelease(2)">发布拼团</button>
      </view>
    </template>
    <uni-popup ref="popup" type="bottom">
      <view class="uni-bg-white fs-14">
        <view class="flex justify-between item-center h-40" style="border-bottom:1px solid #f5f5f5;">
          <text class="text-color-hint p-10" @click="close">收起</text>
          <text class="color-secondary-info p-10" @click="onConfirm">确定</text>
        </view>
        <view class="mt-30 font-bold mx-16">已选标签（最多3个）</view>
        <view class="mx-16 flex flex-wrap">
          <view v-for="(tag, index) in selectTags" :key="index" class="tag-view uni-bg-white mr-12 mt-12">
            <view class="bg-secondary-info text-white radius-16 px-16 py-4">{{ tag.name }}</view>
            <image class="w-13 h-13" src="@/pagesB/static/activity/del-icon.svg" @click="selectTags.splice(i, 1)">
            </image>
          </view>
          <view v-if="selectTags.length < 3" class="tag-view uni-bg-white mt-12" @click="openInputDialog">
            <view class="fs-14 border-secondary-info color-secondary-info radius-16 px-16 py-4">#添加新标签
            </view>
          </view>
        </view>
        <search-bar v-model="tag" @search="onSearch" @clean="onClean" placeholder="搜索标签"></search-bar>
        <view class="mt-16 mb-12 mx-16 font-bold">推荐标签</view>
        <view class="flex flex-wrap uni-bg-white mx-16 tag-content content-start">
          <view v-for="(tag, index) in tagList" :key="index" class="uni-bg-color c3 radius-16 px-16 py-4 mr-12 mb-12" @click="clickTag(tag)">{{ tag.name }}
          </view>
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="inputDialog" type="dialog">
      <uni-popup-dialog ref="inputRef" mode="input" title="添加标签" v-model="newTag" :maxlength="4" placeholder="添加新标签" @confirm="dialogInputConfirm"></uni-popup-dialog>
    </uni-popup>
  </base-page>
</template>

<script setup name="CreateActivity">
import {
  onLoad
} from '@dcloudio/uni-app'
import {
  ref,
  unref,
  computed,
  onUnmounted,
  watch,
  nextTick
} from 'vue'
import {
  releaseGroupBuyApi,
  businessActiveUpdateApi,
  myActiveDetailApi
} from '@/api/business.js'
import {
  getRecommendsApi,
  searchTagApi,
  addTagApi
} from '../api/tag.js'
import {
  uploadFileApi
} from '@/api/common.js'
import {
  SubsidyDict
} from '@/utils/dict.js'
import {
  useUserStore
} from '@/stores/modules/user.js'
import FormEditor from './components/form-editor/form-editor.vue'
import Datetimerange from './components/datetimerange.vue'
import GoodsTable from './components/goods-table.vue'
import RichEditor from '@/pagesE/components/rich-editor/rich-editor.vue'
import {
  getPositionApi
} from '@/api/index.js'
import {
  isVideoFile,
  diffDay,
  floorNumber,
  numberFormat,
  modelShowToastAsync
} from '@/utils/index.js'
import DragImage from '../components/drag-image/drag-image.vue'
import {
  usePublishStore
} from '@/stores/modules/publish.js'
import { cloneDeep, isEqual } from 'lodash-es';


const publishStore = usePublishStore()
const userStore = useUserStore()

const from = ref('')
const newTag = ref('')
const tag = ref('')
const popup = ref(null)
const inputDialog = ref(null)
const inputRef = ref(null)
const tagList = ref([])
const selectTags = ref([])
const open = () => {
  selectTags.value = JSON.parse(JSON.stringify(formData.value.labels))
  popup.value && popup.value.open()
  getRecommends()
}
const close = () => {
  popup.value && popup.value.close()
}
const getRecommends = () => {
  getRecommendsApi().then(res => {
    tagList.value = res
  })
}
const onConfirm = () => {
  formData.value.labels = JSON.parse(JSON.stringify(selectTags.value))
  close()
}
const clickTag = (e) => {
  if (selectTags.value.length >= 3) {
    return showToast('最多选择3个标签')
  }
  selectTags.value.push(e)
}
const openInputDialog = () => {
  inputRef.value.val = ''
  inputDialog.value && inputDialog.value.open()
}
const closeInputDialog = () => {
  inputDialog.value && inputDialog.value.close()
}
const dialogInputConfirm = () => {
  if (!newTag.value.trim()) {
    return showToast('请填写标签名称')
  }
  addTagApi({
    name: newTag.value.trim()
  }).then((res) => {
    selectTags.value.push(res)
    closeInputDialog()
  })
}
const onSearch = () => {
  searchTagApi({
    keyword: tag.value
  }).then(res => {
    tagList.value = res
  })
}

const onClean = () => {
  tag.value = ''
  onSearch()
}
const title = computed(() => {
  switch (formData.value.activeType) {
    case 999:
      return '创建拼团'
    default:
      return '创建拼团'
  }
})

// 是否团购活动
const isGroup = computed(() => {
  return formData.value.activeType != 3
})

/**
 * 是否报名活动
 * 活动类型(1-团购活动，2-报名活动，3-外部活动)
 */
const isSignUp = computed(() => {
  return formData.value.activeType == 2
})

// 是否外部活动
const isLink = computed(() => {
  return formData.value.activeType == 3
})
// 是否零元购
const isZeroState = computed(() => {
  return formData.value.zeroState === 2
})

const storageDataKey = `${userStore.userInfo.id}-groupBuyActivity`;
const goBack = async () => {
  const targetFormData = getCompareFormData();
  if (!isEqual(originFormData, targetFormData)) {
    const isConfirm = await modelShowToastAsync({ confirmText: '保存草稿', content: '您还未保存，请问退出吗？', cancelText: '直接退出' });
    if (isConfirm) {
      uni.setStorage({
        key: storageDataKey,
        data: {
          formData: targetFormData,
          activeGoodsSubsidy: activeGoodsSubsidy.value,
          selectAgentList: selectAgentList.value
        },
        success: () => {
          uni.navigateBack()
        }
      })
      return;
    }
  }
  uni.navigateBack()
}

const getCompareFormData = () => {
  // 为了不影响现有逻辑，构建一个新的对象数据用于比较
  const compareFormData = cloneDeep(formData.value);

  // 填充一些数据，要跟checkInput中的保持一致
  compareFormData.activeImg = files.value.map(f => f.url).join(',') || '';
  if (compareFormData.activeContents?.length) {
    compareFormData.activeContents = compareFormData.activeContents.map((it, i) => ({
      ...it,
      sort: i + 1
    }))
  }
  if (isGroup.value) {
    if (!(compareFormData.enrollEnable !== 1 && (!activeGoods.value || !activeGoods.value.length))) {
      compareFormData.activeGoods = activeGoods.value.map(it => {
        const { id, ...rest } = it
        // 多商户优惠券goodsId已提前拼接好
        if (it.mulState === 2) {
          return { ...it }
        }
        return {
          goodsId: `${id}`,
          id,
          ...rest
        }
      })
    }
    if (compareFormData.subsidyState === 2) {
      compareFormData.activeGoodsSubsidy = activeGoodsSubsidy.value.map(it => {
        const { id, ...rest } = it
        return {
          goodsId: `${id}`,
          id,
          ...rest
        }
      })
    }
  }

  if (compareFormData.activeEnrollInfos && compareFormData.activeEnrollInfos.length) {
    for (let i = 0; i < compareFormData.activeEnrollInfos.length; i++) {
      const item = compareFormData.activeEnrollInfos[i]
      item.sort = i + 1 // 排序值
    }
  }

  if (compareFormData.agentState === 2) {
    // agentNumState 是否是所有经纪人可推广：1-是，2-否
    if (compareFormData.agentNumState === 2) {
      compareFormData.agentIds = agentIds.value
    }
  }

  return compareFormData;
}

const files = ref([])
const MAX_FILE_LENGTH = 6
const toChooseFile = () => {
  uni.chooseMedia({
    count: MAX_FILE_LENGTH - files.value.length, // 最多一个视频，视频+图片不能超过6张
    mediaType: ['mix'], // mix 可同时选择图片和视频
    maxDuration: 30, // 拍摄视频最长拍摄时间，单位秒。时间范围为 3s 至 30s 之间
    sourceType: ['album', 'camera'],
    camera: 'back',
    success: ({
      tempFiles
    }) => {
      if (tempFiles && tempFiles.length) {
        for (var i = 0; i < tempFiles.length; i++) {
          const file = tempFiles[i]
          console.log('选择文件', i, file, files.value, tempFiles)
          if (files.value.length > MAX_FILE_LENGTH) {
            return
          }
          if (file.fileType === 'video') {
            const hasAdd = files.value.some(f => f.fileType === 'video')
            if (hasAdd) {
              showToast('至多只能上传1个视频')
            } else {
              uploadFile(file, files)
            }
          } else {
            uploadFile(file, files)
          }
        }
      }
    }
  })
}

const uploadFile = (file, files) => {
  uni.showLoading()
  uploadFileApi(2, {
    name: 'file',
    filePath: file.tempFilePath
  }).then(res => {
    uni.hideLoading()
    if (res.code === 200) {
      files.value.push(file)
      file.url = res.data
    } else {
      uni.showToast({
        icon: 'none',
        title: res.message
      })
    }
  })
}

const deleteFile = (index) => {
  files.value.splice(index, 1)
}

const delImage = (done) => {
  done()
}

const activeDatetimerange = ref(null) // 活动起止时间
const validDatetimerange = ref(null) // 使用时间

const onActiveDatetimeChange = (val) => {
  if (val) {
    const len = diffDay(val[1], val[0])
    if (len > 360) {
      showToast('活动时间不可超过360天')
      return
    }
    if (formData.value.validStartTime && new Date(formData.value.validStartTime.replace(/-/g, '/')).getTime() <
      new Date(val[0].replace(/-/g, '/')).getTime()) {
      showToast('活动开始时间需早于使用开始时间')
      formData.value.startTime = ''
      formData.value.endTime = ''
      activeDatetimerange.value = null
      return
    }
    formData.value.startTime = val[0]
    formData.value.endTime = val[1]
    activeDatetimerange.value = val
  }
}

const onValidDatetimeChange = (val) => {
  // console.log(diffDay(val[0]),diffDay(formData.value.startTime),'ddd')
  if (val) {
    const len = diffDay(val[1], val[0])
    // 活动有效时间：活动订单可核销的时间，不可超过360天
    if (len > 360) {
      showToast('使用时间不可超过360天')
      return
    }
    if (formData.value.startTime && new Date(val[0].replace(/-/g, '/')).getTime() < new Date(formData.value
      .startTime.replace(/-/g, '/')).getTime()) {
      showToast('使用开始时间应该不能早于活动开始时间')
      formData.value.validStartTime = ''
      formData.value.validEndTime = ''
      validDatetimerange.value = null
      return
    }
    formData.value.validStartTime = val[0]
    formData.value.validEndTime = val[1]
    validDatetimerange.value = val
  }
}

/**
 * 显示不可编辑原因
 * 未开始：活动即将开始，不支持修改
 * 进行中：活动进行中，无法修改
 */
const showDisableTip = () => {
  if (isNotStart.value) {
    showToast('活动即将开始，不支持修改')
    return true
  } else if (isOngoing.value) {
    showToast('活动进行中，无法修改')
    return true
  }
  return false
}
const changeGroupCreatorPermission = () => {
  if (showDisableTip()) {
    return
  }
  formData.value.groupCreatorPermission = formData.value.groupCreatorPermission === 'ALL' ? 'LEVEL1_AGENT' : 'ALL';
};
// 是否零元购
const changeZeroState = () => {
  if (showDisableTip()) {
    return
  }
  formData.value.zeroState = formData.value.zeroState === 1 ? 2 : 1
  formData.value.subsidyState = 1
  if (formData.value.zeroState === 2) {
    formData.value.stepPriceState = 1
    formData.value.activeStepPrices = []
    formData.value.discountState = 1
    formData.value.activeDiscount = []
    formData.value.defaultCommissionType = 0
    formData.value.commissionAmt = ''
    formData.value.commissionRate = ''
    formData.value.groupBuyPrice = 0
    activeGoodsSubsidy.value = []
    formData.value.activeRedPacket = ''
  }
}
// 修改核销方式
const changeVerifyMethod = (type) => {
  if (showDisableTip()) {
    return
  }
  formData.value.verifyMethod = type
}

// 活动商品列表 (团购)
const activeGoods = computed(() => publishStore.goodsList)

// 活动商品变动后更新手动补贴设置
watch(() => activeGoods.value, selectedGoods => {
  console.log('watch 商品', selectedGoods, activeGoods)
  if (formData.value.subsidyState === 2) {
    const newList = []
    for (let i = 0; i < activeGoods.value.length; i++) {
      const goods = activeGoods.value[i]
      // 相同的商品已有补贴设置
      const oldGoodsSubsidy = activeGoodsSubsidy.value
        .filter(it => {
          // 多商户券
          if (it.mulState === 2) {
            return it.goodsId == goods.goodsId && it.mulState === goods.mulState && it
              .goodsName === goods.goodsName && it.goodsPrice == goods.goodsPrice && it
                .details == goods.details
          } else {
            return it.goodsId == goods.goodsId && it.mulState === goods.mulState
          }
        }) || []
      // console.log('原来的商品补贴设置', oldGoodsSubsidy)
      if (oldGoodsSubsidy.length) {
        // 商品数量不变，保留原来的补贴设置
        if (goods.goodsNum === oldGoodsSubsidy.length) {
          for (let j = 0; j < oldGoodsSubsidy.length; j++) {
            newList.push({
              ...goods,
              goodsNum: 1,
              subsidyAmt: oldGoodsSubsidy[j].subsidyAmt
            })
          }
        } else if (goods.goodsNum < oldGoodsSubsidy.length) {
          // 数量有删减
          // 按值大小重新排序，优先保留有值的
          oldGoodsSubsidy.sort((a, b) => b.subsidyAmt - a.subsidyAmt)
          // console.log('排序后的', oldGoodsSubsidy)
          for (let j = 0; j < goods.goodsNum; j++) {
            newList.push({
              ...goods,
              goodsNum: 1,
              subsidyAmt: oldGoodsSubsidy[j].subsidyAmt
            })
          }
        } else {
          // 数量有增加
          // 1.先保留原来的
          for (let j = 0; j < oldGoodsSubsidy.length; j++) {
            newList.push({
              ...goods,
              goodsNum: 1,
              subsidyAmt: oldGoodsSubsidy[j].subsidyAmt
            })
          }
          // 2.再新增的补贴状态初始化
          for (let j = 0; j < goods.goodsNum - oldGoodsSubsidy.length; j++) {
            newList.push({
              ...goods,
              goodsNum: 1,
              subsidyAmt: ''
            })
          }
        }
      } else {
        // 新增商品或未设置补贴，重新生成初始补贴状态
        for (let j = 0; j < goods.goodsNum; j++) {
          newList.push({
            ...goods,
            goodsNum: 1,
            subsidyAmt: ''
          })
        }
      }
    }

    activeGoodsSubsidy.value = newList
    console.log('已有设置补贴', activeGoodsSubsidy.value, '新的补贴设置', newList)
  }
})

// 活动商品补贴列表
const activeGoodsSubsidy = ref([])
const toSubsidySetting = () => {
  if (showDisableTip()) {
    return
  }
  if (activeGoods.value.length <= 0) {
    showToast('请先添加活动商品')
    return
  }
  if (!formData.value.groupBuyPrice && !isZeroState.value) {
    showToast('请填写拼团价格')
    return false
  } else if (+formData.value.groupBuyPrice <= 0 && !isZeroState.value) {
    showToast('拼团价格必须大于0元')
    return false
  }
  uni.navigateTo({
    url: '/pagesG/publish/subsidy-setting',
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', {
        isZeroState: isZeroState.value,
        agentState: unref(formData.value.agentState),
        defaultCommissionType: unref(formData.value.defaultCommissionType),
        commissionAmt: unref(formData.value.commissionAmt),
        commissionRate: unref(formData.value.commissionRate),
        subsidyState: unref(formData.value.subsidyState),
        activeGoods: unref(activeGoods),
        activeGoodsSubsidy: unref(activeGoodsSubsidy),
        activePrice: +formData.value.groupBuyPrice || 0,
        activeRedPacket: formData.value.activeRedPacket && formData.value
          .activeRedPacket.firstRedPacketAmt || 0,
      })
    },
    events: {
      onSubsidyChange: (data) => {
        console.log('onSubsidyChange', data)
        formData.value.subsidyState = data.subsidyState
        activeGoodsSubsidy.value = data.activeGoodsSubsidy
      }
    }
  })
}

// 添加满减折扣
const addDiscount = () => {
  // 最多3个
  if (formData.value.activeDiscount.length >= 3) return
  formData.value.activeDiscount.push({
    discount: null,
    num: null,
  })
}

const onSwitchClick = (stateKey, val) => {

  if (stateKey !== 'hideLink') {
    if (showDisableTip()) {
      return
    }
  }

  if (stateKey === 'discountState') {
    if (isZeroState.value) {
      return
    }
    if (val) {
      formData.value.discountState = 2
      if (formData.value.activeDiscount.length === 0) {
        formData.value.activeDiscount.push({
          discount: null,
          num: null,
        })
      }
    } else {
      formData.value.discountState = 1
    }
  } else if (stateKey === 'agentState') {
    if (val) {
      formData.value.agentState = 2
      if (formData.value.freeType !== 0) {
        showToast('分销与定向免单不可同时开启!');
        formData.value.freeType = 0;
      }
    } else {
      formData.value.agentState = 1
    }
  } else if (stateKey === 'noFullAutoRefundState') {
    if (val) {
      formData.value.noFullAutoRefundState = 1
    } else {
      formData.value.noFullAutoRefundState = 2
    }
  } else if (stateKey === 'verifyType') {
    if (val) {
      formData.value.verifyType = 1
      formData.value.verifyMethod = 2 // 走票付通的活动，核销方式，仅支持线下核销
    } else {
      formData.value.verifyType = 0
    }
  } else if (stateKey === 'enrollEnable') {
    if (val) {
      formData.value.enrollEnable = 1
      formData.value.signInRequired = 1
    } else {
      formData.value.enrollEnable = 0
    }
  } else if (stateKey === 'freeType') {
    formData.value[stateKey] = val;
    if (val && formData.value.agentState !== 1) {
      showToast('分销与定向免单不可同时开启!');
      formData.value.agentState = 1;
    }
    if (val === 1 && formData.value.leadFreeEnabled) {
      showToast('团长免单不可与0元开团同时开启!');
      formData.value.leadFreeEnabled = 0;
    }
  } else if (stateKey === 'leadFreeEnabled') {
    formData.value[stateKey] = val ? 1 : 0;
    if (val && formData.value.freeType === 1) {
      showToast('团长免单不可与0元开团同时开启!');
      formData.value.freeType = 0;
    }
  } else {
    formData.value[stateKey] = val ? 1 : 0
  }
}

const selectAgentList = ref([])
// 分销经纪人用户列表，如果是所有经纪人，则传空，否则传经纪人用户id集合
const agentIds = computed(() => [...selectAgentList.value])

const toDistributionSetting = () => {
  if (showDisableTip()) {
    return
  }
  if (!formData.value.activeTitle) {
    showToast('请填写活动标题')
    return
  }
  formData.value.activeImg = files.value.map(f => f.url).join(',') || ''
  if (!formData.value.activeImg) {
    showToast('请上传活动图片')
    return
  }
  let groupBuyPrice = 0
  if (isSignUp.value) {
    // 开启阶梯价格
    // if(formData.value.stepPriceState === 2) {
    // 	// formData.value.activePrice = 0
    // 	if (formData.value.activeStepPrices && formData.value.activeStepPrices.length > 0) {
    // 		let minObj
    // 		formData.value.activeStepPrices.forEach((it, i) => {
    // 			if (i === 0) {
    // 				minObj = it
    // 			} else {
    // 				if (minObj && +minObj.enrollNum > +it.enrollNum) {
    // 					minObj = it
    // 				}
    // 			}
    // 		})
    // 		activePrice = minObj && +minObj.enrollPrice
    // 	} else {
    // 		showToast('请填写阶梯报名价格')
    // 		return
    // 	}
    // } else {
    // 	if (!formData.value.activePrice && !isZeroState.value) {
    // 		showToast('请填写报名价格')
    // 		return
    // 	} else if (+formData.value.activePrice <= 0  && !isZeroState.value) {
    // 		showToast('报名价格必须大于0元')
    // 		return
    // 	}
    // 	activePrice = +formData.value.activePrice
    // }
    if (!formData.value.groupBuyPrice && !isZeroState.value) {
      showToast('请填写拼团价格')
      return
    } else if (+formData.value.groupBuyPrice <= 0 && !isZeroState.value) {
      showToast('拼团价格必须大于0元')
      return
    }
    groupBuyPrice = +formData.value.groupBuyPrice
  } else {
    if (!formData.value.groupBuyPrice && !isZeroState.value) {
      showToast('请填写拼团价格')
      return
    }
    groupBuyPrice = +formData.value.groupBuyPrice
  }

  uni.navigateTo({
    url: '/pagesG/publish/distribution-setting',
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', {
        activeTitle: unref(formData.value.activeTitle),
        activeImg: unref(formData.value.activeImg),
        activePrice: groupBuyPrice,
        defaultCommissionType: unref(formData.value.defaultCommissionType),
        commissionAmt: unref(formData.value.commissionAmt),
        commissionRate: unref(formData.value.commissionRate),
        otherEquity: unref(formData.value.otherEquity),
        rewardType: unref(formData.value.rewardType),
        rewardPoints: unref(formData.value.rewardPoints),
        agentNumState: unref(formData.value.agentNumState),
        selectAgentList: [...selectAgentList.value],
        isZeroState: isZeroState.value
      })
    },
    events: {
      onCommissionChange: (data) => {
        console.log('分销设置', data)
        formData.value.defaultCommissionType = data.defaultCommissionType
        formData.value.commissionAmt = +data.commissionAmt || ''
        formData.value.commissionRate = +data.commissionRate || ''
        formData.value.otherEquity = data.otherEquity
        formData.value.rewardType = data.rewardType
        formData.value.rewardPoints = data.rewardPoints
        formData.value.agentNumState = data.agentNumState
        selectAgentList.value = data.selectAgentList
      }
    }
  })
}

// 打开地图选择位置
const toChooseLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      console.log('选址', res)
      formData.value.address = res.address
      getPositionApi({
        latitude: res.latitude,
        longitude: res.longitude
      }).then((resp) => {
        formData.value.provinceName = resp.province
        formData.value.cityName = resp.city
        formData.value.countyName = resp.countyName
      })
    }
  })
}

// 新人红包
const toRedPacketSetting = () => {
  if (showDisableTip()) {
    return
  }
  uni.navigateTo({
    url: '/pagesG/publish/red-packet-setting',
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', {
        activeRedPacket: unref(formData.value.activeRedPacket),
      })
    },
    events: {
      onRedPacketChange: (data) => {
        formData.value.activeRedPacket = data
      }
    }
  })
}

// 阶梯价格开关变化
const onStepPriceStateChange = (check) => {
  if (isZeroState.value) {
    return
  }
  if (showDisableTip()) {
    return
  }
  formData.value.stepPriceState = check ? 2 : 1
}
// 添加阶梯价格,最多支持3个
const toAddStepPrice = () => {
  if (showDisableTip()) {
    return
  }
  if (formData.value.activeStepPrices.length < 3) {
    formData.value.activeStepPrices.push({
      enrollNum: '',
      enrollPrice: '',
    })
  }
}
// 删除阶梯价格
const toDeleteStepPrice = (i) => {
  if (showDisableTip()) {
    return
  }
  formData.value.activeStepPrices.splice(i, 1)
}

const isDraft = computed(() => {
  return formData.value && (!formData.value.activeState || formData.value.activeState === 1) // 未发布，草稿状态
})

// 是否已发布，未开始
const isNotStart = computed(() => {
  return false
  // return formData.value && formData.value.activeState === 2 // 未开始
})

// 是否已发布，进行中
const isOngoing = computed(() => {
  return formData.value && formData.value.activeState === 3 // 进行中
})

// 已添加活动商品价格总和
const allGoodsPrice = computed(() => {
  return activeGoods.value && activeGoods.value.reduce((pre, cur) => {
    return pre + cur.goodsNum * (+cur.goodsPrice)
  }, 0) || 0
})

// 分销佣金
const commission = computed(() => {
  if (formData.value.agentState === 2) {
    if (formData.value.defaultCommissionType === 1) {
      return formData.value.commissionAmt
    } else if (formData.value.defaultCommissionType === 2) {
      return +floorNumber((formData.value.groupBuyPrice * formData.value.commissionRate) / 100)
    } else {
      return 0
    }
  } else {
    return 0
  }
})

// 单订单总补贴金额
const subsidyTotal = computed(() => {
  // 套餐内所有商品价格-活动价格+单个红包金额=单订单总补贴金额
  let totalGoodsPrice = allGoodsPrice.value
  const activeRedPacket = formData.value.activeRedPacket && formData.value.activeRedPacket
    .firstRedPacketAmt || 0
  return +floorNumber(totalGoodsPrice - (+formData.value.groupBuyPrice) + activeRedPacket + commission.value)
})

const formData = ref({
  id: '',
  activeTitle: '',
  activeImg: '', // 多个用','分隔
  activeContents: [], // 活动内容
  labels: [], // 活动标签
  activePrice: '', // 活动价格
  originPrice: '', // 划线价格
  totalStock: '', // 活动库存
  signInFee: '', // 签到费用
  limitBuyNum: '', // 限购数量
  subsidyState: 1, // 补贴设置(0-未设置,1-自动按比例分摊,2-手动设置)
  discountState: 1, // 多件多折状态(1-关闭，2-开启)
  activeDiscount: [], // 多件多折列表，最多3个
  agentState: 1, // 分销开启状态(1-关闭，2-开启)
  defaultCommissionType: 0, // 默认佣金类型：0-无，1-佣金，2-佣金比例
  commissionAmt: '', // 分销佣金金额
  commissionRate: '', // 分销佣金比例
  otherEquity: '', // 其他权益
  agentNumState: 1, // 是否是所有经纪人可推广：1-是，2-否
  stepPriceState: 1, // 是否是阶梯价格(1-否，2-是)
  refundableExpiredUnused: 1, // 部分核销是否能退款（0-不能 1-能）
  noFullAutoRefundState: 2, // 未满员是否自动退款:1-是，2-否；默认关闭
  signInRequired: 0, // 是否需要签到（0-否 1-是）
  auditRequired: 0, // 是否需要审核（0-否 1-是）
  hideLink: 0, // 隐藏链接（0-不隐藏 1-隐藏）
  labelIds: [], // 活动标签ids
  enrollEnable: 0, // 开启报名（0-不开启 1-开启）
  enrollNum: '', // 报名人数
  verifyMethod: 2, // 核销方式(1-线上核销，2-线下核销) 必填，默认不选择
  verifyType: 0, // 核销方式（只对报名活动有效）：0-系统，1-票付通
  pftSupplier: '', // 票付通供应商ID
  pftProduct: '', // 票付通产品ID
  pftTicket: '', // 票付通门票ID
  activeStepPrices: [], // 阶梯价格列表
  activeEnrollInfos: [], // 报名信息列表
  startTime: '', // 活动开始时间，格式：yyyy-MM-dd HH:mm:ss
  endTime: '', // 活动结束时间，格式：yyyy-MM-dd HH:mm:ss
  validStartTime: '', // 活动有效开始时间，格式：yyyy-MM-dd HH:mm:ss
  validEndTime: '', // 活动有效结束时间，格式：yyyy-MM-dd HH:mm:ss
  address: userStore.locationInfo.address || '', // 活动详细地址
  provinceName: userStore.locationInfo.provinceName,
  cityName: userStore.locationInfo.cityName || '',
  countyName: '',
  rewardType: 1,
  rewardPoints: '',
  activeRedPacket: '', // 新人首单红包
  zeroState: 1, //是否是零元购活动（1-不是，2-是）
  activeGoods: [], // 活动商品列表
  activeGoodsSubsidy: [], // 活动商品补贴列表
  activeMobile: '', // 活动联系电话
  activeState: 1, // 活动状态（1-仅保存，2-去发布）
  activeType: 4, // 活动类型(1-团购活动，2-报名活动，3-外部活动, 4-团购+报名活动)
  "activeUrl": "", // 活动链接
  "activeWechat": "", // 活动客服微信号
  "agentIds": [], // 分销经纪人用户列表，如果是所有经纪人，则传空，否则传经纪人用户id集合
  "businessId": 0, // 商家id
  "cityId": 0, // 市id
  "countyId": 0, // 区县id
  "directJoinEnabled": 0, // 直接参团开关 (0: 关闭, 1: 开启)
  "freeType": 0, // 免单类型 (0-无，1: 团长免单, 2: 随机免单)
  "groupBuyPrice": '', // 拼团价格
  "groupCreatorPermission": "ALL", // 开团权限 (ALL: 所有人, LEVEL1_AGENT: 一级经纪人)
  "groupDuration": '', // 成团时间（小时
  "groupNum": '', // 成团人数
  "leadFreeEnabled": 0, // 团长0元开团开关 (0: 关闭, 1: 开启)
  "leadViewEnrollInfo": 0, // 报名信息团长是否可见 (0: 不可见, 1: 可见)
  "limitEnrollNum": 0, // 报名次数限制(同个用户最多可报名几次)
  "promotionType": "GROUP_BUY", // GROUP_BUY(拼团)
  "provinceId": 0, // 省份id
  "virtualGroup": 0, // 是否虚拟成团 (0: 否, 1: 是),
  autoRefundEnabled: 0, // 过期自动退款：0：关闭 1-开启
})

let originFormData = {};

// 判断是否有输入
const isNotInput = (val) => {
  return val === null || val === undefined || val === ''
}

const checkInput = () => {
  if (!formData.value.activeTitle) {
    showToast('请填写活动标题')
    return false
  }
  formData.value.activeImg = files.value.map(f => f.url).join(',') || ''
  if (!formData.value.activeImg) {
    showToast('请上传活动图片')
    return false
  } else if (files.value.length === 1) {
    // 不能仅上传一个视频
    if (isVideoFile(files.value[0].url)) {
      showToast('请至少上传一张图片')
      return false
    }
  }

  if (!(formData.value.activeContents && formData.value.activeContents.length > 0)) {
    showToast('请填写活动内容')
    return false
  } else {
    formData.value.activeContents = formData.value.activeContents.map((it, i) => ({
      ...it,
      sort: i + 1
    }))
  }

  if (isGroup.value) {
    if (formData.value.enrollEnable !== 1 && (!activeGoods.value || !activeGoods.value.length)) {
      showToast('请添加活动商品')
      return false
    } else {
      // goodsId赋值
      formData.value.activeGoods = activeGoods.value.map(it => {
        const {
          id,
          ...rest
        } = it
        // 多商户优惠券goodsId已提前拼接好
        if (it.mulState === 2) {
          return {
            ...it
          }
        }
        return {
          goodsId: `${id}`,
          ...rest
        }
      })
    }
    if (formData.value.subsidyState === 0 && +subsidyTotal.value > 0) {
      showToast('请选择补贴设置')
      return false
    } else if (formData.value.subsidyState === 2) {
      // 校验补贴金额是否等于订单补贴金额
      let totalSubsidyAmt = 0
      for (var i = 0; i < activeGoodsSubsidy.value.length; i++) {
        const item = activeGoodsSubsidy.value[i]
        totalSubsidyAmt += +item.subsidyAmt || 0
        if (+item.subsidyAmt > item.goodsPrice) {
          uni.showToast({
            icon: 'none',
            title: '补贴金额不能超过商品价格'
          })
          return false
        }
      }
      // 拼团售价 >= 商品总价（即无补贴），不用选择补贴方式
      if (+formData.value.groupBuyPrice < +allGoodsPrice.value && totalSubsidyAmt !== +subsidyTotal.value) {
        uni.showToast({
          title: `请修改补贴设置，补贴金额需等于订单补贴金额`,
          icon: 'none'
        })
        return false
      }
      // goodsId赋值
      formData.value.activeGoodsSubsidy = activeGoodsSubsidy.value.map(it => {
        const {
          id,
          ...rest
        } = it
        return {
          goodsId: `${id}`,
          ...rest
        }
      })
    }

    if (!formData.value.totalStock) {
      showToast('请填写活动库存')
      return false
    } else if (+formData.value.totalStock < 1) {
      showToast('活动库存必须大于0个')
      return false
    }
    if (formData.value.virtualSaleNum) {
      if (formData.value.virtualSaleNum * 1 >= formData.value.totalStock * 1) {
        showToast('虚拟销量不能大于等于库存')
        return false
      }
    }
    if (formData.value.virtualSaleNum == 0 && formData.value.virtualSaleNum != '') {
      showToast('虚拟销量请填写整数，不能为0')
      return false
    }
    if (formData.value.enrollEnable === 1) {
      if (!formData.value.activeMobile && !formData.value.activeWechat) {
        showToast('请至少填写一项活动联系信息')
        return false
      }
    }
    if (formData.value.enrollEnable === 1) {
      if (!formData.value.activeMobile && !formData.value.activeWechat) {
        showToast('请至少填写一项活动联系信息')
        return false
      }
    }
    if (formData.value.enrollEnable === 1) {
      if (!formData.value.activeMobile && !formData.value.activeWechat) {
        showToast('请至少填写一项活动联系信息')
        return false
      }
    }
  } else if (isLink.value) {
    if (!formData.value.activeUrl) {
      showToast('请填写外部活动链接')
      return false
    }
  }

  if (isSignUp.value) {
    // 开启阶梯价格
    if (formData.value.stepPriceState === 2) {
      // formData.value.groupBuyPrice = 0
    } else {
      if (!formData.value.groupBuyPrice && !isZeroState.value) {
        showToast('请填写拼团价格')
        return false
      } else if (+formData.value.groupBuyPrice <= 0 && !isZeroState.value) {
        showToast('拼团价格必须大于0元')
        return false
      }
    }

    if (!formData.value.verifyMethod) {
      showToast('请设置核销方式')
      return false
    }

    if (!formData.value.activeMobile && !formData.value.activeWechat) {
      showToast('请至少填写一项活动联系信息')
      return false
    }
  } else {
    if (!formData.value.groupBuyPrice && !isZeroState.value) {
      showToast('请填写拼团价格')
      return false
    } else if (+formData.value.groupBuyPrice <= 0 && !isZeroState.value) {
      showToast('拼团价格必须大于0元')
      return false
    }
  }

  if (!formData.value.groupNum) {
    return showToast('请填写成团人数！');
  }

  if (formData.value.groupNum < 2) {
    return showToast('成团人数不可低于2人!');
  }

  if (formData.value.groupNum % 1 !== 0) {
    return showToast('成团人数为正整数!');
  }

  if (formData.value.groupDuration % 1 !== 0) {
    return showToast('成团时间为正整数!');
  }

  if (formData.value.freeType !== 0 && formData.value.agentState !== 1) {
    return showToast('分销与定向免单不可同时开启!');
  }

  if (formData.value.activeEnrollInfos && formData.value.activeEnrollInfos.length) {
    console.log(formData.value.activeEnrollInfos)
    for (let i = 0; i < formData.value.activeEnrollInfos.length; i++) {
      const item = formData.value.activeEnrollInfos[i]
      item.sort = i + 1 // 排序值
      if (item.type === 1) { // 信息填写项
        if (!item.title) {
          showToast('请填写报名信息标题')
          return false
        }
      } else { // 单选项||多选
        if (!item.title) {
          showToast('请填写报名信息标题')
          return false
        }
        // 判断选项是否为空
        // if (item.activeEnrollInfoOptions && item.activeEnrollInfoOptions.some(it => !it.optionText)) {
        // 	showToast('请填写选项内容')
        // 	return false
        // }
      }
    }
  }

  if (!formData.value.activePrice) {
    showToast('请填写单买价格')
    return false
  } else if (+formData.value.activePrice <= 0) {
    showToast('单买价格必须大于0元')
    return false
  }
  /*
    活动开始时间，不能大于活动结束时间
    活动有效开始时间，不能大于活动有效结束时间
    活动结束时间，不能大于活动有效结束时间
  */
  if (!formData.value.startTime && !formData.value.endTime) {
    showToast('请设置活动时间')
    return false
  }
  if (!isLink && !formData.value.validStartTime && !formData.value.validEndTime) {
    showToast('请设置使用时间')
    return false
  }
  // 分销配置判断
  if (formData.value.agentState === 2) {
    if (formData.value.defaultCommissionType === 0) {
      if (!formData.value.commissionAmt && !formData.value.commissionRate && !formData.value.rewardPoints) {
        showToast('您已开启分销，请设置分销权益')
        return false
      }
    }
    // agentNumState 是否是所有经纪人可推广：1-是，2-否
    if (formData.value.agentNumState === 2) {
      formData.value.agentIds = agentIds.value
    }
    console.log('分销 经纪人', formData.value.agentNumState, agentIds.value, selectAgentList.value)
  }

  return true
}

const toRelease = async (state) => {
  if (isZeroState.value) {
    formData.value.groupBuyPrice = 0
  }
  if (checkInput()) {
    if (formData.value.virtualGroup && formData.value.freeType === 1) {
      const isConfirm = await modelShowToastAsync({ content: '您同时开启了虚拟成团和定向免单，可能出现一个团仅团长一人，且团长免单的情况，请注意做好成本控制!' });
      if (!isConfirm) return;
    }
    if (activeGoods.value.length > 0 && formData.value.enrollEnable === 1 && formData.value.verifyMethod !== 2) {
      modelShowToastAsync({ content: '当前是非纯报名活动，核销方式只能线下核销！', showCancel: false });
      return
    }

    uni.showLoading()
    // 已发布活动(未开始、进行中)走更新接口
    const apiMethod = [2, 3].includes(formData.value.activeState) ? businessActiveUpdateApi : releaseGroupBuyApi
    if (from.value === 'copy') {
      formData.value.id = ''
    }
    apiMethod(unref({
      ...formData.value,
      // activePrice: formData.value.groupBuyPrice,
      refundableExpiredUnused: 1, // 开启
      activeState: state // 活动状态，未发布：（1-仅保存，2-去发布）；已发布：更新状态不变
    })).then(res => {
      console.log('发布', res, from.value, getCurrentPages())
      uni.hideLoading()
      originFormData = cloneDeep(formData.value);
      if (res) {
        if (state === 1) {
          if (!formData.value.id && typeof res === 'number') {
            formData.value.id = res
          }
          showToast('保存成功')
          // 进入预览页面
          const url = formData.value.promotionType === 'GROUP_BUY'
            ? `/pagesB/activity/activity-preview-group-buy`
            : `/pagesB/activity/activity-preview`;
          uni.navigateTo({
            url: `${url}?id=${formData.value.id}&from=${from.value}&_from=BCreateGroupBuyActivityItem`
          })
        } else {
          uni.$emit('publishSuccess')
          showToast('发布成功')
          // 进入我的活动列表
          uni.redirectTo({
            url: `/pagesB/my-activity/my-activity?from=${from.value}`
          })
        }
      }
    })
  }
}

const showToast = (title) => {
  uni.showToast({
    title,
    icon: 'none'
  })
}

const initFormData = () => {
  files.value = formData.value.activeImg.split(',').filter(it => it).map(it => ({
    url: it,
    fileType: isVideoFile(it) ? 'video' : 'image'
  }))
  if (typeof formData.value.content === 'string') {
    formData.value.activeContents = formData.value.content && JSON.parse(formData.value.content) ||
      []
  }
  activeGoods.value = formData.value.activeGoods || []
  publishStore.goodsList = formData.value.activeGoods || []
  formData.value.startTime = reformatDatetime(formData.value.startTime)
  formData.value.endTime = reformatDatetime(formData.value.endTime)
  formData.value.validStartTime = reformatDatetime(formData.value.validStartTime)
  formData.value.validEndTime = reformatDatetime(formData.value.validEndTime)
  activeDatetimerange.value = [formData.value.startTime, formData.value.endTime]
  validDatetimerange.value = [formData.value.validStartTime, formData.value.validEndTime]
}

const getDetail = () => {
  myActiveDetailApi(formData.value.id).then(res => {
    res.virtualSaleNum = res.virtualSaleNum === 0 ? '' : res.virtualSaleNum
    formData.value = {
      ...res.activeGroupBuy,
      ...res,
    }
    if (from.value === 'copy') {
      formData.value.id = ''
      formData.value.activeRedPacket = ''
      delete formData.value.activeState
    }
    formData.value.limitBuyNum = res.limitBuyNum || ''
    console.log('草稿箱', res, formData.value.content)
    initFormData()
    activeGoodsSubsidy.value = res.activeGoodsSubsidy
    selectAgentList.value = res.agentIds || []

    originFormData = cloneDeep(formData.value);
  })
}

// 时间格式从yyyy.MM.dd HH:mm:ss 格式化为yyyy-MM-dd HH:mm:ss
const reformatDatetime = (date) => {
  const reg = new RegExp(/\./g)
  return date && date.replace(reg, '-') || ''
}

onLoad(options => {
  console.log('创建活动', options, publishStore.goodsList)
  from.value = options.from
  publishStore.reset()
  formData.value.id = +options.id || ''
  formData.value.activeType = +options.type
  if (formData.value.id) {
    getDetail()
  } else {
    uni.getStorage({
      key: storageDataKey,
      success: (res) => {
        formData.value = res.data.formData;
        initFormData()
        activeGoodsSubsidy.value = res.data.activeGoodsSubsidy
        selectAgentList.value = res.data.agentIds || []

        originFormData = getCompareFormData();
      },
      fail: () => {
        originFormData = getCompareFormData();
      },
    })
  }
})

onUnmounted(() => {
  publishStore.reset()
})
</script>
<style scoped lang="scss">
.line {
  height: 1rpx;
  background: #d5d5d5;
}

.tag-view {
  border-radius: 16px;
  position: relative;

  image {
    position: absolute;
    top: -2px;
    right: -4px;
  }
}

.tag-content {
  min-height: 300px;
}
</style>